//
//  CancelOrderVC.m
//  YueYueSpecailCarDriver
//
//  Created by 李亚军 on 17/3/1.
//  Copyright © 2017年 黄旺鑫. All rights reserved.
//

#import "CancelOrderVC.h"
#import <MJRefresh/MJRefresh.h>
#import <QXDriverConfiguration/QXDriverConfiguration.h>
#import "CancelOrderCell.h"
#import "ComplaintModel.h"
#import "HeaderMacro.h"
#import "DLLApiManager.h"
#import "CancelOrderReasonModel.h"
#import "NotificationNameManager.h"

@interface CancelOrderVC ()<UITableViewDelegate , UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;


/**
 数据源
 */
@property(nonatomic , strong) NSMutableArray *dataSource;

/**
 投诉内容
 */
@property(nonatomic , copy) NSString *contents;

@property (weak, nonatomic) IBOutlet UIBarButtonItem *backItem;

/**
 提交
 */
@property(nonatomic , strong) IBOutlet UIButton *submitBut;


/**
 表头
 */
@property (weak, nonatomic) IBOutlet UIView *headerView;

/**
 取消订单警示label
 例如: 现在取消订单，乘客需支付2.4元超时等待费。
 */
@property (weak, nonatomic) IBOutlet UILabel *cancelWarningLabel;

/**
 取消原因label
 例如: 乘客已迟到，您可取消订单
 */
@property (weak, nonatomic) IBOutlet UILabel *cancelReasonLabel;


/**
 表尾
 */
@property (weak, nonatomic) IBOutlet UIView *footerView;


/**
 取消原因
 */
@property(nonatomic , copy) NSString *cancelReason;


/**
 是否取消订单默认为NO
 */
@property(nonatomic , assign) BOOL isCancelOrder;

@end

@implementation CancelOrderVC

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        self.dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configureDefaultAttributes];
    
    [self configureHeaderViewAndFooterView];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        // 获取取消原因描述
        [self getCancelOrderDescription];
    }];
    [self.tableView.mj_header beginRefreshing];
}

+ (CancelOrderVC *)initCancelOrderVC {
    
    UIStoryboard *ordersStoryboard = [UIStoryboard storyboardWithName:@"Orders" bundle:[NSBundle mainBundle]];
    
    CancelOrderVC *cancelOrderVC = [ordersStoryboard instantiateViewControllerWithIdentifier:@"CancelOrderVCID"];
    
    return cancelOrderVC;
}

- (void)configureDefaultAttributes {
    
    self.isCancelOrder = NO;
    
    // cell 自适应高度
//    self.tableView.estimatedRowHeight = 60.0;
//    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.submitBut.layer.cornerRadius = 5.0;
    self.submitBut.layer.masksToBounds = YES;
    
    
    // 设置返回按钮的图片
    [self.backItem setImage:[QXDriverConfiguration imageWithName:@"nav_icon_back_white"]];
    
    // 刚进入页面是没有表头的
    [self isGetCancelDescritionWithBool:NO];
}


/**
 计算字体大小
 */
- (CGSize)calculateWidthOfString:(NSString *)str fontSize:(NSInteger)fontSize labelH:(NSInteger)labelH labelW:(NSInteger)labelW {
    NSDictionary *attributes = @{NSFontAttributeName : [UIFont systemFontOfSize:fontSize]};
    CGSize size = [str boundingRectWithSize:CGSizeMake(labelW, labelH) options: NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    return size;
}


/**
 配置表头,表尾
 */
- (void)configureHeaderViewAndFooterView {
    
    if (self.dataSource.count > 0) {
        
//        CGFloat headerViewHeight = 0.0;
//        CGFloat height1 = [self calculateWidthOfString:self.cancelReasonLabel.text fontSize:16 labelH:0 labelW:[UIScreen mainScreen].bounds.size.width - 30].height;
//        CGFloat height2 = [self calculateWidthOfString:self.cancelWarningLabel.text fontSize:14 labelH:0 labelW:[UIScreen mainScreen].bounds.size.width - 30].height;
//        headerViewHeight = 20 + height1 + 10 + height2 + 10;
        
        self.footerView.hidden = NO;
        self.footerView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 105);
        self.tableView.tableFooterView = self.footerView;
    }else {
        
        
        self.footerView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 0);
        self.tableView.tableFooterView = self.footerView;
        self.footerView.hidden = YES;
    }
}


#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    // 刷新 UI 的时候,刷新表头,表尾
    [self configureHeaderViewAndFooterView];
    
    if (self.dataSource.count > 0) {
        
        return 1;
    }else {
        
        return 0;
    }
    
};

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSInteger number = self.dataSource.count;
    
    return number;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell;
    
    cell = [self dealCancelOrderCellWithTableView:tableView indexPath:indexPath];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 60;
}

#pragma mark - 投诉列表 Cell UI 处理
- (CancelOrderCell *)dealCancelOrderCellWithTableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath {
    
    CancelOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CancelOrderCellID" forIndexPath:indexPath];
    
    if (indexPath.row < self.dataSource.count) {
        
        CancelOrderReasonModel *model = self.dataSource[indexPath.row];
        
        [cell setValueWithCancelOrderReasonModel:model];
    }
    
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 40)];
    
    UILabel *tittleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, [UIScreen mainScreen].bounds.size.width - 30, CGRectGetHeight(headerView.frame))];
    tittleLabel.font = [UIFont systemFontOfSize:15];
    tittleLabel.textColor = Color_4F5A67;
    tittleLabel.text = @"取消原因";
    tittleLabel.backgroundColor = [UIColor clearColor];
    [headerView addSubview:tittleLabel];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 40;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    for (CancelOrderReasonModel *model in self.dataSource) {
        
        model.isSelected = NO;
    }

    CancelOrderReasonModel *model = self.dataSource[indexPath.row];
    model.isSelected = YES;
    if (model.tagName == nil || model.tagName.length <= 0) {
        
        self.contents = model.tagName;
    }else {
        
        self.contents = @"";
    }

    [self.tableView reloadData];
}




#pragma mark - action
- (IBAction)backAction:(UIBarButtonItem *)sender {
    
    if (self.isCancelOrder) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_DriverCancelOrder object:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }else {
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}


- (IBAction)submitButAction:(UIButton *)sender {
    
    sender.userInteractionEnabled = NO;
    [sender setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateNormal)];
    [self submitComplaintRequest];
    
}

#pragma mark - 提交取消
/**
 查询订单状态
 */
- (void)submitComplaintRequest {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        MBProgressHUD *mb = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        mb.userInteractionEnabled = NO;
    });
    
    NSMutableDictionary *pramaters = [NSMutableDictionary dictionary];
    [pramaters setValue:self.orderUuid forKey:@"orderUuid"]; // 订单
    [pramaters setValue:self.contents forKey:@"cancelMsg"];
    
    __weak typeof(self) weakSelf = self;
    
    [DLLApiManager driverCancelOrderWithParameters:pramaters success:^(id data) {
        
        __strong typeof(self) strongSelf = weakSelf;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:strongSelf.view animated:NO];
        });
        
        if (NetWork_Success) { // 提交成功后操作
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                strongSelf.isCancelOrder = YES;
                [strongSelf backAction:nil];
            });
            
            
        }else {
            
            strongSelf.isCancelOrder = NO;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                MBProgressHUD *mb = [MBProgressHUD showWithText:NetWork_Message onView:nil hiddenDuration:2.0];
                mb.userInteractionEnabled = NO;
            });
        }
        
    } failure:^(NSError *error) {
        
        __strong typeof(self) strongSelf = weakSelf;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            strongSelf.isCancelOrder = NO;
            MBProgressHUD *mb = [MBProgressHUD showWithText:NetWorkNotToForce onView:strongSelf.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
        });
    }];
}

#pragma mark - 订单取消获取说明
- (void)getCancelOrderDescription {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:self.orderUuid forKey:@"orderUuid"];
    __weak typeof(self) weakSelf = self;
    [DLLApiManager driverCancelOrderDescriptionWithParameters:parameters success:^(id data) {
        
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (NetWork_Success) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    NSString *description = data[@"data"][@"description"];
                    NSString *details = data[@"data"][@"details"];
                    if (description.length > 0 || details.length > 0) {
                        
                        [strongSelf isGetCancelDescritionWithBool:YES];
                        strongSelf.cancelReasonLabel.text = description;
                        strongSelf.cancelWarningLabel.text = details;
                        
                        [strongSelf getCancelOrderMsg]; // 获取原因
                        
                    }else {
                        
                        [strongSelf isGetCancelDescritionWithBool:NO];
                        [strongSelf getCancelOrderMsg]; // 获取原因
                    }

                });
                
            }else {
                
                MBProgressHUD *mb = [MBProgressHUD showWithText:NetWork_Message onView:strongSelf.view hiddenDuration:2.0];
                mb.userInteractionEnabled = NO;
            }
        });

    } failure:^(NSError *error) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [strongSelf isGetCancelDescritionWithBool:NO];
            [strongSelf getCancelOrderMsg]; // 获取原因
        });
    }];
}

// 更新表头UI
- (void)isGetCancelDescritionWithBool:(BOOL)isgetCancelDescription {
    
    if (isgetCancelDescription) {
        
        self.headerView.hidden = NO;
        self.headerView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 100);
        self.tableView.tableHeaderView = self.headerView;
    }else {
        
        self.headerView.frame = CGRectMake(0, 0, 0, 0);
        self.tableView.tableHeaderView = self.headerView;
        self.headerView.hidden = YES;
    }
}

#pragma mark - 获取取消原因
- (void)getCancelOrderMsg {
    
    __weak typeof(self) weakSelf = self;
    [DLLApiManager driverCancelOrderMsgListWithParameters:nil success:^(id data) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [strongSelf.dataSource removeAllObjects];
            if (NetWork_Success) {
                
                NSArray *dataArr = data[@"data"];
                if ([dataArr isKindOfClass:[NSArray class]]) {
                    
                    if (dataArr.count > 0) {
                        
                        for (NSDictionary *dataDic in dataArr) {
                            
                            CancelOrderReasonModel *model = [CancelOrderReasonModel new];
                            [model setValuesForKeysWithDictionary:dataDic];
                            model.isSelected = NO;
                            [strongSelf.dataSource addObject:model];
                        }
                    }
                    
                }
                
                [strongSelf.tableView.mj_header endRefreshing];
                [strongSelf.tableView reloadData];
                
            }else {
                
                MBProgressHUD *mb = [MBProgressHUD showHUDAddedTo:strongSelf.view animated:NO];
                mb.userInteractionEnabled = NO;
            }
        });
        
    } failure:^(NSError *error) {
        
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [strongSelf.tableView.mj_header endRefreshing];
            MBProgressHUD *mb = [MBProgressHUD showWithText:NetWorkNotToForce onView:strongSelf.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
        });
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
